/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package huy.ser;

import Easy.table.Users;
import Huytn.sessionBean.ShoppingCartDTO;
import Huytn.sessionBean.UserSessionBean;
import Huytn.sessionBean.UserSessionBeanRemote;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Vector;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.UserTransaction;

/**
 *
 * @author DR.HUY
 */
public class ProcessServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ProcessServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            Context ctx = new InitialContext();
            UserTransaction ut = (UserTransaction)ctx.lookup("UserTransaction");
            UserSessionBeanRemote remote = (UserSessionBeanRemote)ctx.lookup("UserRemoteJNDI");
            Users list;
            HttpSession session = request.getSession();
            UserSessionBean uCart = (UserSessionBean)session.getAttribute("cart");
            String action = request.getParameter("action");
            if(action.equals("Submit")){
               ut.begin();
               String username = request.getParameter("txtUsername");
               String pass = request.getParameter("txtPassword");
               String Cpass = request.getParameter("txtCPassword");
               String name = request.getParameter("txtName");
               String dob = request.getParameter("txtDOB");
               String address = request.getParameter("txtAddress");
               String phone = request.getParameter("txtPhone");
               String email = request.getParameter("txtEmail");

               remote.insertUser(username, pass, name, dob, address, phone, email, "user", "Active");
               ut.commit();
               out.println("Insert Successfully");
           }else if(action.equals("Login")){
               ut.begin();
               String username = request.getParameter("txtUsername");
               String pass = request.getParameter("txtPassword");
               list = remote.login(username, pass);
               ut.commit();
               if(list!=null){
                   if(list.getRole().equals("user")){
                       request.getSession().setAttribute("UserInfo", list);
                       request.getSession().setAttribute("error", "");
                       request.getRequestDispatcher("index.jsp").forward(request, response);
                    }else{
                       request.getSession().setAttribute("UserInfo", list);
                       request.getSession().setAttribute("error", "");
                       request.getRequestDispatcher("ProcessServlet?action=Account Management").forward(request, response);
                    }
                }else{
                   request.getSession().setAttribute("error", "Wrong username or password!");
                   request.getRequestDispatcher("login.jsp").forward(request, response);
                }
           }else if(action.equals("logout")){
               session.removeAttribute("UserInfo");
               session.removeAttribute("cart");
               session.removeAttribute("total");
               session.removeAttribute("cardNumb");
               request.getRequestDispatcher("login.jsp").forward(request, response);
           }else if(action.equals("UpdatePassword")){
               request.getRequestDispatcher("updatePassword.jsp").forward(request, response);
           }else if(action.equals("Update Profile")){
//               request.setAttribute("UserInfo", list);
               request.getRequestDispatcher("updateProfile.jsp").forward(request, response);
           }else if(action.equals("Update")){
               String id = request.getParameter("txtID");
               String username = request.getParameter("txtUsername");
               String name = request.getParameter("txtName");
               String dob = request.getParameter("txtDoB");
               String address = request.getParameter("txtAddress");
               String phone = request.getParameter("txtPhone");
               String email = request.getParameter("txtEmail");
               ut.begin();
               remote.updateProfile(Integer.parseInt(id), username, name, dob, address, phone, email);
               ut.commit();
               request.getSession().setAttribute("UserInfo", null);
               request.getRequestDispatcher("login.jsp").forward(request, response);
           }else if(action.equals("Update Password")){
               String id = request.getParameter("txtID");
               String toPass = request.getParameter("txtTOPass");
               String oPass = request.getParameter("txtOPass");
               String nPass = request.getParameter("txtNPass");
               ut.begin();
               if(toPass.equals(oPass)){
                    remote.updatePassword(Integer.parseInt(id), nPass);
                    ut.commit();
                    request.getSession().setAttribute("UserInfo", null);
                    request.getSession().setAttribute("pError", "");
                    request.getRequestDispatcher("login.jsp").forward(request, response);
                }else
                    request.getSession().setAttribute("pError", "Wrong Password");
                    request.getRequestDispatcher("updatePassword.jsp").forward(request, response);

           }else if(action.equals("Account Management")){
               ut.begin();
               Users[] users = remote.loadUsers("user");
               ut.commit();
               request.getSession().setAttribute("Load", users);
               request.getRequestDispatcher("AdAccount.jsp").forward(request, response);
           }else if(action.equals("Disable")){
               String id = request.getParameter("txtID");
               ut.begin();
               if(remote.disableUser(Integer.parseInt(id), "Disable")){
               ut.commit();
               request.getRequestDispatcher("ProcessServlet?action=Account Management").forward(request, response);
               }else
                   out.println("Fail");
           }else if(action.equals("Active")){
               String id = request.getParameter("txtID");
               ut.begin();
               if(remote.disableUser(Integer.parseInt(id), "Active")){
               ut.commit();
               request.getRequestDispatcher("ProcessServlet?action=Account Management").forward(request, response);
               }else
                   out.println("Fail");
           }else if(action.equals("AddCart")){
               String name = request.getParameter("txtTicketName");
               int quan = Integer.parseInt(request.getParameter("txtQuan"));
               int price = Integer.parseInt(request.getParameter("txtPrice"));
               int de = Integer.parseInt(request.getParameter("txtDetail"));
               ShoppingCartDTO dto = new ShoppingCartDTO(name, de, 1, quan, price);
               if(uCart == null){
                   uCart = new UserSessionBean();
               }
               uCart.addTicket(dto);
               session.setAttribute("cart", uCart);
               request.getRequestDispatcher("shoppingCart.jsp").forward(request, response);
           }else if(action.equals("Remove")){
               int i = Integer.parseInt(request.getParameter("index"));
                uCart.removeTicket(i-1);
                if(uCart.getContents().isEmpty()){
                    session.removeAttribute("cart");
                    request.getRequestDispatcher("shoppingCart.jsp").forward(request, response);
                }
                session.setAttribute("cart", uCart);
                request.getRequestDispatcher("shoppingCart.jsp").forward(request, response);
            }
            else if(action.equals("updateCart")){
                int i = Integer.parseInt(request.getParameter("index"));
                 String name = request.getParameter("name");
               int quan = Integer.parseInt(request.getParameter("quan"));
               int maxQuan = Integer.parseInt(request.getParameter("maxQuan"));
               int price = Integer.parseInt(request.getParameter("price"));
               int de = Integer.parseInt(request.getParameter("id"));
               if(quan>maxQuan){
                   session.setAttribute("cartError", "Don't have enough ticket");
                   request.getRequestDispatcher("shoppingCart.jsp").forward(request, response);
               }else{
                    ShoppingCartDTO dto = new ShoppingCartDTO(name, de, quan, maxQuan , price);
                    uCart.editTicket(i-1, dto);
                    session.setAttribute("cart", uCart);
                    session.setAttribute("cartError", "");
                    request.getRequestDispatcher("shoppingCart.jsp").forward(request, response);
                }
            }else if(action.equals("Check Out")){
                request.getRequestDispatcher("checkCredit.jsp").forward(request, response);
            }else if(action.equals("Check Credit card")){
                int total = (Integer)session.getAttribute("total");
                String cardNum = request.getParameter("cardNum");
                session.setAttribute("cardNumb", cardNum);
                if(remote.checkCredit(cardNum, total).equals("wrongCard")){
                    session.setAttribute("cError", "Wrong card number!");
                    request.getRequestDispatcher("checkCredit.jsp").forward(request, response);
                }else if(remote.checkCredit(cardNum, total).equals("notEnough")){
                    session.setAttribute("cError", "Balance is not enough!");
                    request.getRequestDispatcher("checkCredit.jsp").forward(request, response);
                }
                else if(remote.checkCredit(cardNum, total).equals("enough")){
                    session.setAttribute("cError", "");
                    request.getRequestDispatcher("createOrder.jsp").forward(request, response);
                }

            }else if(action.equals("Create Order")){
               list = (Users)session.getAttribute("UserInfo");
               String cardNum = (String)session.getAttribute("cardNumb");
               String total = Integer.toString((Integer)session.getAttribute("total"));
               String date = request.getParameter("date");
               String add = request.getParameter("dAdd");
               remote.insertOrder(list.getUserID(), cardNum, total, date, add, "Waiting");
               UserSessionBean shop = (UserSessionBean) session.getAttribute("cart");
               int count = 0;
               Vector v = shop.getContents();
               Enumeration item = v.elements();
               while (item.hasMoreElements()) {
                    count++;
                    ShoppingCartDTO dto = (ShoppingCartDTO) item.nextElement();
                    int orderId = remote.selectOrderId();
                    int quantity = dto.getQuantity();
                    int ticketId = dto.getTicketID();
                    remote.insertOrderDetail(orderId, ticketId, quantity);
               }
               session.removeAttribute("cart");
               session.removeAttribute("total");
               session.removeAttribute("cardNumb");
               request.getRequestDispatcher("index.jsp").forward(request, response);
            }

            out.println("</body>");
            out.println("</html>");
        }catch(Exception e){
            e.printStackTrace();
        } finally { 
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
